import 'package:bloc/bloc.dart';
import 'package:flutter/material.dart';
import 'package:qgchat/common/action/filter/index.dart';
import 'package:qgchat/common/global/global.dart';
import 'package:qgchat/http/apis/common.dart';
import 'package:qgchat/http/models/resModel.dart';

enum ReleaseDynamicEvent { release, reset }

class ReleaseDynamicBloc extends Bloc<ReleaseDynamicEvent, List<String>> {
  @override
  List<String> get initialState => [];

  @override
  Stream<List<String>> mapEventToState(ReleaseDynamicEvent event) async* {
    switch (event) {
      // 发布动态
      case ReleaseDynamicEvent.release:
        _release();
        break;
      // 刷新图
      case ReleaseDynamicEvent.reset:
        List<String> currentState = _imgs.map((i) => i).toList();
        loding = false;
        yield currentState;
        break;
    }
  }

  TextEditingController c = TextEditingController(); // 输入框控制器
  List<String> _imgs = []; // 图片列表
  bool loding = false;  // 正在上传图
  FocusNode focus = FocusNode(); // 焦点

  String get _text => isSetText ? c.text : null; // 发布时的文字
  int get imgsLength => _imgs.length; // 图片数量
  bool get isSetText => c.text.length > 0; // 是否输入了文字
  bool get isMaxText => c.text.length > 256; // 最大字数限制
  bool get isSetImgs => _imgs.length > 0; // 是否上传了图片
  bool get isMaxImgs => _imgs.length > 9; // 最大图片数限制

  /// 发布动态
  _release() async {
    if (!isSetText && !isSetImgs) {
      showToast("未输入内容");
      return;
    }
    if (isMaxText) {
      showToast("文字最多256个字符");
      return;
    }
    if (isMaxImgs) {
      showToast("图片最多9张");
      return;
    }

    ResModel res = await CommonApis.senddongtai(Filter.txt(_text), img: _imgs);
    showToast(res.msg);
    if (res.status == 1) {
      Global.noCtxRoute.navigateBack();
    }
  }

  /// 上传图片
  addImg(String url) {
    _imgs.add(url);
  }

  /// 删除图片
  delImg(int i) {
    _imgs.removeAt(i);
  }
}